
var map;
var markersArray = [];
var markerClustererArray = [];
var infowindow = new google.maps.InfoWindow();
var  infoBubble = new InfoBubble({
                              maxWidth: 300
                              });
var infoBubbleImg = document.createElement('img');
var contactDIV = document.createElement('DIV');
var markerCluster, markerCluster1, markerCluster2, markerCluster3;
google.maps.event.addDomListener(window, 'load', initialize);
console.log('Javascript from file OK');


function initialize() {
    
    var myLatlng = new google.maps.LatLng(55.750089,52.601591);
    var mapOptions = {
    zoom: 4,
    center: myLatlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById('map_canvas'),
                              mapOptions);
    markerCluster = new MarkerClusterer(map);
    
    mcOptionsPass = {minimumClusterSize: 2 ,zoomOnClick: false,
                              styles: [{
                              height: 60,
                              url: "foss_gr1-2.png",
                              width: 60
                              }]}
    
    markerCluster1 = new MarkerClusterer(map, [], mcOptionsPass);
    

    mcOptionsWar = {minimumClusterSize: 3 ,zoomOnClick: false,
                             styles: [{
                             height: 60,
                             url: "foss_gr2-2.png",
                             width: 60
                             }]}
    markerCluster2 = new MarkerClusterer(map, [], mcOptionsWar);
    
    mcOptionsEr = {minimumClusterSize: 3 ,zoomOnClick: false,
                            styles: [{
                            height: 60,
                            url: "foss_gr3-2.png",
                            width: 60
                            }]}
//    infoBubble = new InfoBubble({
//                                     maxWidth: 300
//                                     });
    
    var div = document.createElement('DIV');
    div.innerHTML = 'Hello';
    
    infoBubble.addTab('Tab 1', div);
    infoBubble.addTab('Tab 2', "<B>This is tab 2</B>");
    infoBubble.addTab('Tab 3', "<B>This is tab 3</B>");
    
    markerCluster3 = new MarkerClusterer(map, [], mcOptionsEr);
    createDB();
    
    loadPins("point.json");
    
    
    
    
//    showAll();
    
//    var mcOptions = {gridSize: 50, maxZoom: 15};
//    mClastS = new MarkerClusterer(map, [], mcOptions);
//    mClastP = new MarkerClusterer(map, [], mcOptions);
//    mClastW = new MarkerClusterer(map, [], mcOptions);
//    mClastEr = new MarkerClusterer(map, [], mcOptions);
    
//    var marker = new google.maps.Marker({
//                                        position: myLatlng,
//                                        map: map,
//                                        title: 'Hello World!'
//                                        });
};
function clearPins() {


//    markersArray=[];
//
//    for (var i = 0; i < markerClustererArray.length; i++ ) {
////        markerClustererArray[i].setMap(null);
//        markerClustererArray[i].clearMarkers();
//    }
//    markerClustererArray.length = 0;
    
    markerCluster.clearMarkers();
    markerCluster1.clearMarkers();
    markerCluster2.clearMarkers();
    markerCluster3.clearMarkers();
    
    for (var i = 0; i < markersArray.length; i++ ) {
        markersArray[i].setMap(null);
    }
    markersArray.length = 0;
    
//    markerClustererArray=[];
    
};

function getStatus(type){
    if (type==1)
    {
        return '<font color="green">Passed</font>';
    }
    if (type==2)
    {
        return '<font color="yellow">Warning</font>';
    }
    if (type==3)
    {
        return '<font color="red">Error</font>';
    }
    return '<font color="gray">Disabled</font>';
}

function  showAll(){
    clearPins();
    console.log('showAll');
    showAllPins("SELECT * FROM mPins");
}
function showPas(){
    
//    markerCluster = new MarkerClusterer(map, markersArray);
    infoBubble.close();
    clearPins();
    console.log('showPass');
    showAllPins("SELECT * FROM mPins WHERE type=0 or type=1");
}
function showWar(){
    infoBubble.close();
    clearPins();
    console.log('showWar');
    showAllPins("SELECT * FROM mPins WHERE type=0 or type=2");
}
function showEr(){
    infoBubble.close();
    clearPins();
    console.log('showErr');
    showAllPins("SELECT * FROM mPins WHERE type=0 or type=3");
}

function showAllPins(sqlStr) {
    
    if(!db){
        db = openDatabase("dbMap", "0.1", "A list of points.", 200000);
        console.log('Data Base open connection');
        if(!db){
            alert("Failed to connect to database.");
        }
    }else{console.log('Data Base was find');}
    if(sqlStr==null){
        sqlStr="SELECT * FROM mPins";
    }


//    var markerClusterer = new MarkerClusterer(map, [], {
//                                          maxZoom: zoom,
//                                          gridSize: size,
//                                          styles: styles[style]
//                                          });
    db.transaction(function(tx) {
                   tx.executeSql(sqlStr, [],
                                 function(tx, result) {
                                     for(var i = 0; i < result.rows.length; i++) {
                                         var row = result.rows.item(i)
                                         //add new pin
                                         console.log(row['address']+row['ident']);
                                         if((row['lat']==0)&&(row['longt']==0)){
                                             continue;
                                         }
                                         var myLatlng = new google.maps.LatLng(row['lat'],row['longt']);
                                         var marker;
                                 
                                         if(row['type']==0){
                                 
                                            marker = new google.maps.Marker({
                                                                  position: myLatlng,
                                                                  icon:'pin1-1.png',
                                                                  map: map,
                                                                  title: row['address']
                                                                  });
//                                            markerCluster.addMarker(marker);

                                         }else if(row['type']==1){
                                            var markerImage = new google.maps.MarkerImage('icon_passed-2.png',null,null,null,
                                                                               new google.maps.Size(20, 30));
                                            marker = new google.maps.Marker({
                                                                 position: myLatlng,
                                                                 icon:'icon_passed-2.png',
                                                                 map: map,
                                                                 title: row['address']
                                                                 });
                                            markerCluster1.addMarker(marker);
                                         }else if(row['type']==2){
                                 var markerImage = new google.maps.MarkerImage('icon_warning-2.png',null,null,null,
                                                                               new google.maps.Size(20, 30));
                                            marker = new google.maps.Marker({
                                                                 position: myLatlng,
                                                                 icon:'icon_warning-3.png',
                                                                 map: map,
                                                                 title: row['address']
                                                                 });
                                            markerCluster2.addMarker(marker);
                                         }else if(row['type']==3){
                                 var markerImage = new google.maps.MarkerImage('icon_error-2.png',null,null,null,
                                                                               new google.maps.Size(20, 30));
                                            marker = new google.maps.Marker({
                                                                 position: myLatlng,
                                                                 icon:'icon_error-3.png',
                                                                 map: map,
                                                                 title: row['address']
                                                                 });
                                            markerCluster3.addMarker(marker);
                                         }
                                 
                               
                                 
                                 var statusContentString =
                                 '<h1 id="firstHeading" class="firstHeading">'+row['address']+'</h1>'+
                                 '<div id="bodyContent">'+
                                 '<p><b>Synchronisation Status: </b>'+getStatus( row['SynchronisationFlag'])  +
                                 '<p><b>Events Status: </b>'+getStatus(row['EventsFlag'])+
                                 '<p><b>Diagnostics Status: </b>'+getStatus(row['DiagnosticFlag'])    +
                                 '<p><b>Outlier Status: </b>'+getStatus(row['OutlierFlag'])    +
                                 '<p><b>Product Limits Status: </b>'+getStatus(row['ProductLimitsFlag'])  +
                                 '<p><b>World Map Status: </b>'+getStatus(row['type'])+
                                 '</div>';
                                 marker.statusHtml =statusContentString;
                                 
                                 var infoContentString =
                                 '<div id="bodyContent">'+
                                 '<p><b>Name:</b><br>'+ row['name']  +
                                 '<p><b>Network Name:</b><br>'+row['address']+
                                 '<p><b>Instrument Group Name:</b><br>'+row['GroupName']    +
                                 '<p><b>Serial Number:</b><br>'+row['SerialNumber']    +
                                 '<p><b>Installed At:</b><br>'+row['InstalledAtUTC'].substring(0,10)  +' '+row['InstalledAtUTC'].substring(11,16)+
                                 '<p><b>Registered At:</b><br>'+row['RegisteredAtUTC'].substring(0,10)  +' '+row['RegisteredAtUTC'].substring(11,16) +
                            
                                 '</div>';
                               
                                 var infoContactString =
                                 '<div id="bodyContent">'+
                                 '<p><b>Owner:  </b>'+ ((row['FirstName'] !=null) ? row['FirstName'] : '')  +' '+((row['LastName'] != null) ? row['LastName'] : '')  +
                                 '<p><b>Office Phone:  </b>'+ ((row['OfficePhone'] != null) ? row['OfficePhone'] : '')+
                                 '<p><b>Cell Phone:  </b>'+((row['CellPhone'] != null) ? row['CellPhone'] : '')   +
                                 '<p><b>Email:  </b>'+((row['Email']  != null ) ? row['Email'] : '')   +
                                 '<br><b>Instrument Picture:</b>'+
                                
                                 '</div>';
                                 marker.statusHtml =statusContentString;
                                 marker.infoContentString =infoContentString;
                                 marker.instrumentImgUrl =row['InstrumentPicture'];
                                 marker.infoContactString =infoContactString;
//                                 '<b>Address:  </b> ' + row['address'];
             
                                 
                                 
                                         google.maps.event.addListener(marker, 'click', function () {
//                                                                       if (!infoBubble.isOpen()) {
//                                                                            infoBubble.open(map, this);
//                                                                       }else{
//                                                                           infoBubble.close();
//                                                                           infoBubble.open(map, this);
//                                                                       }
                                                                       infoBubble.open(map, this);
                                                                       infoBubble.updateTab(1,'STATUS',this.statusHtml);
                                                                       infoBubble.updateTab(0,'INFO',this.infoContentString);
                                                             

                                                                       
                                                                       var xhr = new XMLHttpRequest();
                                                                       xhr.infoContactString=this.infoContactString;
                                                                       xhr.open("GET", this.instrumentImgUrl, false,'fossftp','quoK1quee1eic1');
                                                                       
                                                                       xhr.responseType = 'arraybuffer';
                                                                       
                                                                       xhr.onload = function(e) {
                                                                           if (this.status == 0) {
                                                                           var blob = new Blob([this.response]);
                                                                            infoBubbleImg.src=window.URL.createObjectURL(blob);
                                                                       
                                                                       contactDIV.innerHTML=this.infoContactString;
                                                                       contactDIV.appendChild(infoBubbleImg);
//                                                                            infoBubble.updateTab(2,'img',infoBubbleImg);
                                                                            infoBubble.updateTab(2,'CONTACT',contactDIV);
                                                                           }
                                                                       };
                                                                       
                                                                       xhr.onerror = function(e) {
                                                                           alert("Error " + e.target.status + " occurred while receiving the document.");
                                                                       };
                                                                       
                                                                       xhr.send();
                                                                       
                                                                       
//                                                                       infoBubble.updateTab(0,'img',img);
                                                                       
                                                                       
                                                                       
                                                                       
//                                                                          infowindow.setContent(this.note);
//                                                                          infowindow.open(map, this);
                                         });
                                         markersArray.push(marker);
                                 
                                
                                     }
//                                     markerClustererArray.push(markerCluster);
//                                     markerClustererArray.push(markerCluster1);
//                                     markerClustererArray.push(markerCluster2);
//                                     markerClustererArray.push(markerCluster3);
                                     var passed = document.getElementById('passed');
                                     passed.innerHTML=markerCluster1.markers_.length;
                                     var warning = document.getElementById('warning');
                                     warning.innerHTML=markerCluster2.markers_.length;
                                     var error = document.getElementById('error');
                                     error.innerHTML=markerCluster3.markers_.length;
                                 
                                 }, function (tx, error) {
                                 console.log(error);
                                 })});
    
    
};